package com.gin.kotlin.no_gay_alliance.activity

import android.content.Context
import android.content.Intent
import android.graphics.Typeface
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.text.style.StyleSpan
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import com.gin.kotlin.no_gay_alliance.R
import com.gin.kotlin.no_gay_alliance.adapter.vote.VoteBetAdapter
import com.gin.kotlin.no_gay_alliance.adapter.vote.VoteScoreAdapter
import com.gin.kotlin.no_gay_alliance.adapter.vote.VoteVoteAdapter
import com.gin.kotlin.no_gay_alliance.app.App
import com.gin.kotlin.no_gay_alliance.argument.VoteArgument
import com.gin.kotlin.no_gay_alliance.base.AbstractBindingActivity
import com.gin.kotlin.no_gay_alliance.databinding.ActivityVoteBinding
import com.gin.kotlin.no_gay_alliance.utils.TimeUtils
import com.gin.nga.callback.NgaCallback
import com.gin.nga.enums.VoteResultShow
import com.gin.nga.enums.VoteType
import com.gin.nga.response.base.NgaResponse
import com.gin.nga.response.vote.VoteData
import retrofit2.Call
import retrofit2.Response
import java.time.ZonedDateTime
import java.util.Locale

class VoteActivity : AbstractBindingActivity<ActivityVoteBinding>() {
    private lateinit var data: VoteData
    private lateinit var argument: VoteArgument

    override fun onCreateOptionsMenu(menu: Menu, menuInflater: MenuInflater) {
        super.onCreateOptionsMenu(menu, menuInflater)

        if (data.type == VoteType.VOTE_TOPIC) {
            menuInflater.inflate(R.menu.post, menu)
            menu.findItem(R.id.mi_setting).isVisible = false
        }
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (item.itemId == R.id.mi_send_post && data.type == VoteType.VOTE_TOPIC) {
            val end = data.end
            if (end!=null && ZonedDateTime.now().isAfter(end)){
                handler?.toast("截止时间已过")
                return true
            }

            // 投票
            val checked = (b?.recyclerView?.adapter as? VoteVoteAdapter)?.checked?.map { it.id } ?: return false

            App.INSTANCE.ngaApi.topicReadApi.vote(argument.topicId, checked).enqueue(object : NgaCallback<List<String>> {
                override fun onSuccess(
                    call: Call<NgaResponse<List<String>>>,
                    response: Response<NgaResponse<List<String>>>,
                    body: NgaResponse<List<String>>?,
                    data: List<String>?
                ) {
                    data?.get(0)?.also { toast(it) }
                }

                override fun onError(call: Call<NgaResponse<List<String>>>, response: Response<NgaResponse<List<String>>>, body: NgaResponse<List<String>>?, errorMessage: String) {
                    toastLong(errorMessage)
                }
            })
            return true
        }

        return super.onOptionsItemSelected(item)
    }

    override fun onCreate() {
        val b = this.b ?: return
        this.data = argument.getVoteData() ?:return

        b.tvTitle.text = null
        b.tvTitle.visibility = View.GONE

        b.tvDescription.text = SpannableStringBuilder().also { builder ->
            appendText(builder, "参与人数", " ${data.total} ", "  ")
            when (data.type) {
                VoteType.VOTE_TOPIC -> {
                    appendText(builder, "总票数", " ${data.totalCount} ", "\n")
                }

                VoteType.BET_TOPIC -> {
                    appendText(builder, "总投注", " ${data.totalMoney} ", "铜\n")
                    appendText(builder, "投注范围", " ${data.min} ~ ${data.max}", "\n")
                }

                else -> {}
            }
            data.maxSelect?.takeIf { it > 0 }?.also { appendText(builder, "(每组)最多选择", " $it ", "项\n") }
            data.reputation?.also { appendText(builder, "声望不低于", " $it ", "\n") }
            data.end?.also { appendText(builder, "截止时间", " ${TimeUtils.SIMPLE_DATE_TIME_FORMATTER.format(it)} ", "\n") }
            when (data.show) {
                VoteResultShow.AFTER_VOTE -> builder.append("投票后显示结果\n")
                VoteResultShow.AFTER_END -> builder.append("结束后显示结果\n")
                else -> {}
            }
        }

        when (data.type) {
            VoteType.VOTE_TOPIC -> b.recyclerView.adapter = VoteVoteAdapter(this, handler!!, data.options).also {
                it.maxSelect = data.maxSelect ?: 1
            }

            VoteType.BET_TOPIC -> b.recyclerView.adapter = VoteBetAdapter(this, handler!!, data.options).also {
                it.successId = data.successId
                it.min = data.min
                it.end = data.end
                it.max = data.max
                it.topicId = argument.topicId
            }
            VoteType.SCORE_TOPIC -> {
                b.recyclerView.adapter = VoteScoreAdapter(this, handler!!, data.scoreResults)
                // 标题和平均分
                val score = String.format(Locale.CHINESE, "%.2f", 1.0 * data.totalScore!! / data.total)
                b.tvTitle.visibility = View.VISIBLE
                b.tvTitle.text = "${data.title} ${score}"
            }

            else -> {}
        }
    }

    private fun appendText(builder: SpannableStringBuilder, prefix: String, text: String, suffix: String) {
        builder.append(prefix)
        builder.append(text)
        val colorSpan = ForegroundColorSpan(getAttrColor(R.attr.textColorBlue))
        builder.setSpan(colorSpan, builder.length - text.length, builder.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        // 加粗
        builder.setSpan(StyleSpan(Typeface.BOLD_ITALIC), builder.length - text.length, builder.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        builder.append(suffix)
    }

    override fun onResume() {
        super.onResume()
        setToolbarTitle(
            when (data.type) {
                VoteType.VOTE_TOPIC -> "投票"
                VoteType.BET_TOPIC -> "投注"
                VoteType.SCORE_TOPIC -> "评分"
                else -> ""
            }
        )
    }

    override fun handleIntent(intent: Intent) {
        this.argument = parseArgument(intent, VoteArgument::class.java.simpleName, VoteArgument::class.java)
    }

    companion object {
        @JvmStatic
        fun start(context: Context, argument: VoteArgument) =
            context.startActivity(Intent(context, VoteActivity::class.java).putExtra(VoteArgument::class.java.simpleName, argument))
    }
}